use macroquad::prelude::{
    draw_rectangle, draw_texture_ex, vec2, DrawTextureParams, Font, Texture2D, Vec2, BLACK, WHITE,
};

use crate::{
    html::flatten,
    label::{Label, FONT_SIZE},
    user::UserCache,
};

pub struct Post {
    pub content: String,
    pub user_finger: String,
}

pub struct PostWidget {
    message: Label,
    avatar: Texture2D,
    avatar_size: Vec2,
    max_char_width: u32,
}

impl PostWidget {
    pub fn new(post: &Post, users: &UserCache) -> Self {
        let def = Self::default();
        let extracted_text = flatten(&post.content);
        return Self {
            message: Label::new(&extracted_text).fit(def.max_char_width),
            avatar: Self::find_user_avatar(&post.user_finger, users),
            ..def
        };
    }
    fn find_user_avatar(finger: &str, users: &UserCache) -> Texture2D {
        match users.find_finger(finger) {
            Some(user) => user.avatar,
            None => Texture2D::empty(),
        }
    }

    pub fn height(self: &Self) -> f32 {
        return self
            .avatar_size
            .y
            .max(self.message.height() + FONT_SIZE as f32);
    }
    pub fn width(self: &Self) -> f32 {
        let approx_text_width = 0.55 * (self.max_char_width * FONT_SIZE as u32) as f32;
        return self.avatar_offset() + self.avatar_size.x + self.text_offset() + approx_text_width;
    }

    fn text_offset(self: &Self) -> f32 {
        1.1 * FONT_SIZE as f32
    }

    fn avatar_offset(self: &Self) -> f32 {
        self.avatar_size.x * 0.2
    }

    pub fn draw(self: &Self, x: f32, y: f32, font: Font) {
        draw_rectangle(x, y, self.width(), self.height(), BLACK);
        self.message.draw(
            x + self.avatar_size.x + self.avatar_offset() + self.text_offset(),
            y + self.text_offset(),
            font,
        );

        draw_texture_ex(
            self.avatar,
            x + self.avatar_offset(),
            y + self.avatar_offset(),
            WHITE,
            DrawTextureParams {
                dest_size: Some(self.avatar_size),
                ..Default::default()
            },
        );
    }
}

impl Default for PostWidget {
    fn default() -> Self {
        return PostWidget {
            avatar_size: vec2(50.0, 50.0),
            message: Label::new(""),
            avatar: Texture2D::empty(),
            max_char_width: 30,
        };
    }
}
